<template>
  <div v-loading="pageLoading" class="detail-order-info">
    <template v-if="!permissionDenied">
      <ProgressStep
        v-if="hasApproval && !showMobilePage"
        :mode="2"
        :step-list="stepList"
        :order-status="stepActiveId"
        :is-show-correct="false"
        :is-expedited="detailData.isExpedited"/>
      <explanation v-if="hasApproval" :explanation="explanationObj" :countdown="true" :style="`${showMobilePage ? 'margin-bottom: 0px' : ''}`" @queryProcessData="queryProcessData"/>
      <listDetail :table-data="detailData.scoreList || []"/>
      <formDetail :data="detailData"/>
      <el-image v-if="isRevoke" :src="revokeImg" class="revoke-img"/>
      <ExamineAndApprove
        v-if="hasApproval"
        ref="examineAndApproveRef"
        :disabled="pageLoading"
        :process-id="processId"
        :main-id="id"
        :version="version"
        :get-comments-api="getFilterComments"
        :comment-add-api="filterCommentAdd"
        :process-revocation-api="upProcessRevocation"
        :process-recall-api="upProcessRecall"
        :process-audit-api="filterProcessAudit"
        :create-user="createUser"
        :default-aduitor-list="[]"
        :business-type="BUSINESS_TYPE.BLOGGER_FILTER"
        :process-type="PROCESS_TYPE.BLOGGER_FILTER"
        :audit-schedule-data="auditScheduleData"
        :senders="senders"
        :approval-module-type="APPROVAL_MODULE_TYPE.BLOGGER_FILTER"
        :print-data="detailData"
        next-approve-module-id="id"
        redirect-url="/supplierPage/filterDetail"
        detail-page-router-name="filterDetail"
        edit-page-router-name="filterEdit"
        @toBack="toBack"
        @setProcessData="setProcessData"
        @handlePressSend="handlePressSend"
        @getAuditSchedule="getAuditSchedule"
        @queryProcessData="queryProcessData"
        @handleModify="handleModify('filterEdit',{id},{remodifyId: processId})"
        @handleSendMsg="handleSendMsg"
        @handleSender="handleSender"
        @getHistoryDetail="getHistoryDetail"
        @setCurrentVersion="setCurrentVersion"
        @handleCancelPress="handleCancelPress"
        @freshDetail="getUpDetail"
      >
        <div slot="signUp">
          <el-button v-if="showSignBtn" size="small" type="primary" @click="handleSignUp">发起签约</el-button>
        </div>
      </ExamineAndApprove>
      <fixed-pagination v-else>
        <div class="center">
          <el-dropdown v-if="showMobilePage" style="margin-right: 10px;" trigger="click" class="mobile-btn-flex" placement="bottom">
            <el-button size="small">更多</el-button>
            <el-dropdown-menu slot="dropdown" style="padding: 0;">
              <el-dropdown-item v-if="showScoreBtn" style="text-align: center" @click.native="handleScore">
                <div>评分</div>
              </el-dropdown-item>
              <el-dropdown-item v-if="showInviteBtn" style="text-align: center" @click.native="handleInvite">
                <div>邀请评分</div>
              </el-dropdown-item>
              <el-dropdown-item v-if="showApprovalBtn" style="text-align: center" @click.native="getProcessDetail">
                <div>发起审批</div>
              </el-dropdown-item>
              <el-dropdown-item v-if="showEditBtn" style="text-align: center" @click.native="handleEdit">
                <div>编辑</div>
              </el-dropdown-item>
              <el-dropdown-item v-if="showDelBtn" style="text-align: center" @click.native="handleDelete">
                <div>删除</div>
              </el-dropdown-item>
              <el-dropdown-item v-if="showSignBtn" style="text-align: center" @click.native="handleSignUp">
                <div>发起签约</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <div v-else>
            <el-button v-if="showScoreBtn" size="small" type="primary" @click="handleScore">评分</el-button>
            <el-button v-if="showInviteBtn" size="small" type="primary" @click="handleInvite">邀请评分</el-button>
            <el-button v-if="showApprovalBtn" size="small" type="primary" @click="getProcessDetail">
              <div class="flex-center">发起审批<InfoIcon content="账号存在沟通异议或需要特批申请时才需发起审批" class="tip-icon" /></div>
            </el-button>
            <el-button v-if="showEditBtn" size="small" plain type="primary" @click="handleEdit">编辑</el-button>
            <el-button v-if="showDelBtn" :loading="delLoading" size="small" plain type="danger" @click="handleDelete">删除</el-button>
            <el-button v-if="showSignBtn" size="small" type="primary" @click="handleSignUp">发起签约</el-button>
          </div>
          <el-button :class="{'ml10': !showMobilePage}" class="cancel-btn-style" size="small" @click="handleBack">返回列表</el-button>
        </div>
      </fixed-pagination>
      <inviteDialog ref="inviteDialog" @update="getUpDetail"/>
      <scoreDialog ref="scoreDialog" @update="getUpDetail"/>
    </template>
    <DeniedPlaceholder v-else />
    <ding-ding-dialog
      ref="pressSendDialogRef"
      :btn1="'确认加急'"
      :btn2="'取消'"
      :show-send-checkbox="false"
      :select-with-user-load="false"
      :default-list="pressDefaultList"
      redirect-url="/supplierPage/filterDetail"
      summary-title="加急原因"
      title="催办通知"
      @handelOK="toSend" />
    <audit-process
      ref="auditProcess"
      :loading="pageLoading"
      v-model="auditInfo"
      :default-aduitor-list="[userInfo]"
      :flow-structure="processDetail"
      :current-process-index="Number(currentProcessIndex)"
      @submit="submit(SUBMIT_TYPE.SUBMIT)" />
  </div>
</template>
<script>
import formDetail from '../components/formDetail';
import listDetail from '../components/listDetail';
import inviteDialog from '../components/inviteDialog';
import scoreDialog from '../components/scoreDialog';
import ProgressStep from '@/components/CreateOrder/orderDetail/step';
import ExamineAndApprove from '@/components/Common/ExamineAndApprove';
import AuditProcess from '@/components/Common/auditProcess';
import explanation from '@/components/Common/explanation';
import schedule from '@/mixins/schedule';
import processCreate from '@/mixins/processCreate';
import mobileCreate from '@/mixins/mobileCreate';
import {
  upDetail,
  deleteUp,
  getFilterComments,
  filterCommentAdd,
  filterProcessAudit,
  formSubmit,
  launchFilter,
  upProcessRecall,
  upProcessRevocation
} from '@/api/filter';
import { PROGRESS_STEP } from '@/utils/const/energy';
import { hasRouteAuth } from '@/utils/permission';
import ElMessage, { showModal } from '@/utils/message';
import { BUSINESS_TYPE, PROCESS_TYPE, FIXED_PROCESS_TYPE } from '@/utils/const/process';
import { APPROVAL_MODULE_TYPE } from '@/utils/const';
import { createAuditStructure } from '@/utils/aduitor';
import { SUBMITTYPE as SUBMIT_TYPE } from '@/utils/const/cost';
import { mapState } from 'vuex';
import math from '@/utils/math';
import revokeImg from '@/assets/auditProcess/process_status_3.png';

export default {
  components: {
    formDetail,
    listDetail,
    inviteDialog,
    scoreDialog,
    ProgressStep,
    AuditProcess,
    explanation,
    ExamineAndApprove
  },
  mixins: [schedule, processCreate, mobileCreate],
  data() {
    return {
      revokeImg,
      PROGRESS_STEP,
      APPROVAL_MODULE_TYPE,
      BUSINESS_TYPE,
      PROCESS_TYPE,
      SUBMIT_TYPE,
      getFilterComments,
      filterCommentAdd,
      upProcessRevocation,
      upProcessRecall,
      filterProcessAudit,
      id: '',
      detailData: {},
      pageLoading: false,
      stepActiveId: PROGRESS_STEP.PENDING,
      processId: '', // 流程id
      permissionDenied: false, // 详情页是否可查看
      delLoading: false,
      processData: {// 流程信息
        list: [],
        operation: {
          auth: [],
          content: null
        }
      },
      auditInfo: {
        activeTime: null,
        isSigner: 0,
        countersignSet: 0,
        process: [],
        senders: [],
        id: null
      },
      isRevoke: false,
      processDetail: null
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage,
      'userInfo': state => state.user.userInfo
    }),
    isCreator() {
      return this.detailData.creatorId === this.userInfo.id;
    },
    // 发起过审批
    hasApproval() {
      return this.processId || typeof this.detailData.approvalStatus === 'number';
    },
    // 评分
    showScoreBtn() {
      // 未发起过审批，isScore为true，且为评分中，有权限，才能评分
      const { isScore, result } = this.detailData;
      return !this.hasApproval && isScore && result === 1 && hasRouteAuth('crm:filter:score');
    },
    // 邀请评分
    showInviteBtn() {
      // 未发起过审批，初筛结果为待提交或不合格，不为草稿中，有权限，才能邀请评分
      const { result, status } = this.detailData;
      return !this.hasApproval && [0, 3].includes(result) && status !== 0 && hasRouteAuth('crm:filter:invite');
    },
    isEditAuth() {
      let isDept = this.hasRouteAuth('crm:filter:departmentEdit');
      if (isDept) {
        isDept = this.userInfo.currentDepartment.some(i => {
          return i.id === this.detailData.createDepartmentId;
        }) || this.isCreator;
      }
      // <!-- 初筛结果为待提交或不合格，有权限才能编辑 -->
      return [0, 3].includes(this.detailData.result) && (hasRouteAuth('crm:filter:edit') || isDept);
    },
    // 编辑
    showEditBtn() {
      return !this.hasApproval && this.isEditAuth;
    },
    // 删除
    showDelBtn() {
      const { result, approvalStatus } = this.detailData;
      // 初筛结果为待提交或不合格，有权限才能删除
      const canDel = [0, 3, 5].includes(result) && hasRouteAuth('crm:filter:delete');
      if (this.hasApproval) {
        // 发起审批仅未过审可删除
        return canDel && approvalStatus === 2;
      }
      return canDel;
    },
    // 发起签约
    showSignBtn() {
      const { result, approvalStatus } = this.detailData;
      // 初筛结果为合格/合格(特批)且有权限才显示
      const canLaunch = [2, 4].includes(result) && hasRouteAuth('crm:filter:signUp');
      if (this.hasApproval) {
        // 审批通过
        return canLaunch && approvalStatus === 4;
      }
      return canLaunch;
    },
    // 发起审批
    showApprovalBtn() {
      return !this.hasApproval && this.detailData.result === 3 && this.isCreator;
    },
    createUser() {
      let user = { id: this.detailData.creatorId, userName: this.detailData.creator };
      if (this.isCreator) {
        user = this.userInfo;
      }
      return user;
    },
    stepList() {
      return [
        { name: '待提交', id: PROGRESS_STEP.PENDING },
        { name: '审批中', id: PROGRESS_STEP.UNDER_REVIEW },
        { name: '已完成', id: PROGRESS_STEP.FINISHED }
      ];
    }
  },
  created() {
    this.initData();
  },
  methods: {
    hasRouteAuth,
    initData() {
      this.initRouteData();
      this.queryProcessData(); // 流程数据
    },
    initRouteData() {
      this.id = this.$route.query.id;
      this.processId = this.$route.query.processId;
      if (!this.id) {
        this.$message.warning('无法获取ID');
        const timer = setTimeout(() => {
          this.$router.back();
          clearTimeout(timer);
        }, 1500);
      }
    },
    queryProcessData() {
      this.getUpDetail();
      if (this.processId) {
        this.getAuditSchedule();
        this.$nextTick(() => {
          this.$refs.examineAndApproveRef && this.$refs.examineAndApproveRef.getProcessList();
        });
      }
    },
    getUpDetail() {
      this.pageLoading = true;
      upDetail(this.id).then(res => {
        this.pageLoading = false;
        if (res.code === 200) {
          this.handleDetailData(res);
          if (this.hasApproval) {
            this.handleProcessCheck(res.data.processId);
          }
        }
      }).catch(err => {
        if (err.code === 403) {
          this.permissionDenied = true;
        }
        this.pageLoading = false;
      });
    },
    // 处理详情接口返回的数据
    handleDetailData(res) {
      if (res.data.shareRatio) {
        res.data.talentSharingRatio = String(math.subtract(100, Number(res.data.shareRatio)));
      }
      if (res.data.processStatus === 3) { // 3为撤销
        this.isRevoke = true;
      } else {
        this.stepActiveId = res.data.processStatus;
        this.isRevoke = false;
      }
      this.detailData = res.data;
    },
    getAuditSchedule() {
      this.requestAuditSchedule(this.processId);
    },
    handleScore() {
      this.$refs.scoreDialog.openDialog(this.id);
    },
    handleInvite() {
      this.$refs.inviteDialog.openDialog(this.id);
    },
    handleEdit() {
      this.$router.push({ name: 'filterCreate', query: { id: this.id }});
    },
    handleDelete() {
      showModal('是否确定删除?', '', {
        iconClass: 'del-icon'
      }).then(() => {
        this.delLoading = true;
        deleteUp(this.id).then(_ => {
          ElMessage.success('删除成功');
          this.handleBack();
        }).finally(_ => {
          this.delLoading = false;
        });
      }).catch(() => {
        return false;
      });
    },
    handleSignUp() {
      const routeUrl = this.$router.resolve({
        name: 'signUpCreate',
        query: { filterId: this.id }
      });
      window.open(routeUrl.href, '_blank');
    },
    handleBack() {
      this.$router.push({ name: 'filter' });
    },
    setProcessData(processData) {
      this.processData = processData;
    },
    getProcessDetail() {
      this.pageLoading = true;
      const params = {};
      params.id = this.id;
      params.type = FIXED_PROCESS_TYPE.BLOGGER_FILTER;
      formSubmit(params).then(res => {
        this.pageLoading = false;
        if (res.code === 200) {
          this.processDetail = res.data;
          this.auditInfo.activeTime = res.data.activationTime;
          this.auditInfo.id = res.data.id;
          // 创建人回填
          this.auditInfo.process = createAuditStructure(res.data.process, this.userInfo, this.userInfo);
          this.auditInfo.senders = res.data.senderDiyUserList || [];
          this.$refs['auditProcess'].openDrawer();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        this.pageLoading = false;
        console.log(err);
      });
    },
    submit(submitType = SUBMIT_TYPE.SUBMIT) {
      const params = {};
      params.id = this.id;
      params.type = FIXED_PROCESS_TYPE.BLOGGER_FILTER;
      params.submitType = submitType;
      params.isEditAudit = false;
      params.auditInfo = this.auditInfo;
      showModal('请确认是否发起审批？').then(_ => {
        this.add(params);
      });
    },
    add(params) {
      launchFilter(params).then(res => {
        if (res.code === 200) {
          this.$message.success('发起成功');
          if (res.data.id && res.data.processId) {
            this.$router.push({
              name: 'filterDetail',
              query: { id: res.data.id, processId: res.data.processId }
            });
          } else {
            this.toBack();
          }
        } else {
          ElMessage.error(res.message);
        }
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcess'].setShowRefresh(true);
        }
        this.loading = false;
      });
    },
    toBack() {
      if (this.$route.query.fromTodo) {
        this.$router.go(-1);
      } else {
        this.$router.push({ name: 'filter' });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.detail-order-info {
  margin: 16px;
  min-height: calc(100vh - 80px);
  padding: 20px 20px 55px;
  background: #fff;
  &.mobile-detail-wrap {
    padding: 12px 12px 55px 12px;
  }
  &::v-deep {
    .el-form-item {
      margin-bottom: 0;
      &.indentation-form-item {
        label {
          line-height: 1.2 !important;
        }
      }
    }
    .el-form-item .el-form-item__label {
      color: #999;
    }
    .el-form-item .el-form-item__content {
      color: #333;
    }
    .order-detail-step {
      padding: 0;
      margin-bottom: 16px;
    }
    .dividing{
      .el-col {
        .el-form-item__content {
          border-right: 1px solid #EBEEFD;
        }
        &:nth-child(3n) {
          .el-form-item__content {
            border-right: none;
          }
        }
        &:last-child {
          .el-form-item__content {
            border-right: none;
          }
        }
      }
    }
  }
  .mb26 {
    margin-bottom: 26px;
  }
  .ml10 {
    margin-right: 10px;
  }
  .tip-icon {
    width: 16px;
    height: 16px;
    margin-left: 4px;
    filter: brightness(2);
    &:hover {
      filter: brightness(999) !important;
    }
  }
  .revoke-img{
    position: absolute;
    width: 80px;
    height: 80px;
    right: 56px;
    top: 33px;
    z-index: 999;
  }
}
</style>
